import os
import yaml
import threading
import argparse
import subprocess

def startDdmd(cmd):
    # os.system(cmd)
    subprocess.run([cmd], shell=True)



def start(env_dir, nCpu):
    with open(env_dir + '/ddmdconfs.yaml') as f:
        parsed = yaml.safe_load(f)
        threads = []
        with open(env_dir + '/start.sh', 'w') as f1:
            f1.write('#!/bin/bash\n')
        for conf in parsed['ddmdConfs']:
            cpu_str = ''
            if nCpu != None:
                cpu_str = '-XX:ActiveProcessorCount=%d' % nCpu
            cmd = 'nohup java ' + cpu_str + ' -jar ddmd.jar -n' + conf['name'] + ' -p ' + str(conf['port']) + ' -f ' + conf['fib'] + ' &'
            with open(env_dir + '/start.sh', 'a') as f1:
                f1.write(cmd + '\n')
            continue
            t = threading.Thread(target=startDdmd, args=(cmd,))
            t.start()
            threads.append(t)
        for t in threads:
            t.join()
            

# start('envs/i2/ddmdconfs.yaml')

def genI2DdmdConf(topo_file, output):
    confs = []
    devices = []
    for line in open(topo_file):
        arr = line.split()
        if arr[0] not in devices:
            devices.append(arr[0])
        if arr[2] not in devices:
            devices.append(arr[2])

    port = 6001
    for node in devices:
        dconf = {'name': node, 'port': port,
                'fib': 'dataset/internet2/rule/' + node + 'ap'}
        confs.append(dconf)
        port += 1

    ddmd_confs = {'ddmdConfs': confs}
    with open(output, 'w') as f:
        yaml.dump(ddmd_confs, f)

def genDdmdConf(env_dir, port):
    confs = []
    devices = []
    for line in open(env_dir + '/' + 'topo.txt'):
        arr = line.split()
        if arr[0] not in devices:
            devices.append(arr[0])
        if arr[2] not in devices:
            devices.append(arr[2])

    for node in devices:
        dconf = {'name': node, 'port': port,
                'fib': env_dir + '/rules/' + node}
        confs.append(dconf)
        port += 1

    ddmd_confs = {'ddmdConfs': confs}
    out_file = env_dir + '/gen/' + 'ddmdconfs.yaml'
    os.makedirs(os.path.dirname(out_file), exist_ok=True)
    with open(out_file, 'w') as f:
        yaml.dump(ddmd_confs, f)

    
if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('e', help='the folder of environment')
    parser.add_argument('-g', action="store_true", help='generate ddmd confs')
    parser.add_argument('-s', action="store_true", help='simulation network')
    parser.add_argument('-c', type=int, help='avaliable cpu cores')
    parser.add_argument('-p', type=int, default='8000', help='assign port start at')
    args = parser.parse_args()
    if args.g:
        genDdmdConf(args.e, args.p)
    if args.s:
        start(args.e, args.c)
    


# genI2DdmdConf('dataset/internet2/topology.txt', 'envs/i2/ddmdconfs.yaml')